﻿
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;

using Kalman;
using Newtonsoft.Json.Linq;

namespace QuDao
{
    /// <summary>
    /// 数据表sys_role关联的业务对象，处理该表相关的业务逻辑
    /// </summary>
    public sealed partial class RoleBO : SingletonBase<RoleBO>
    {
        readonly IFreeSql fsql;
        public RoleBO() : base()
        {
            fsql = ServiceLocator.Instance.GetRequiredService<IFreeSql>();
        }

        #region Generate Code

        /// <summary>
        /// 获取系统角色
        /// </summary>
        /// <param name="id">主键ID的值</param>
        /// <returns></returns>
        public T GetItem<T>(int id)
        {
            var item = fsql.Select<Role>().Where(a => a.RoleID == id).ToOne<T>();
            return item;
        }

        /// <summary>
        /// 获取系统角色数据列表
        /// </summary>
        /// <returns></returns>
        public List<T> GetList<T>(int[] ids)
        {
            var list = fsql.Select<Role>().Where(a => ids.Contains(a.RoleID)).ToList<T>();
            return list;
        }

        /// <summary>
        /// 新增系统角色
        /// </summary>
        public int Add(Role entity)
        {
            entity.CreateTime = DateTime.Now;
            entity.ModifyTime = DateTime.Now;
            entity.RoleID = (int)fsql.Insert(entity).ExecuteIdentity();
            return entity.RoleID;
        }

        public int SetEnable(int id, bool isEnable)
        {
            return fsql.Update<Role>(id).Set(a => a.IsEnable, isEnable).ExecuteAffrows();
        }

        /// <summary>
        /// 删除系统角色数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public void Delete(int id)
        {
            fsql.Transaction(() =>
            {
                fsql.Delete<Role>().Where(a => a.RoleID == id).ExecuteAffrows();
                fsql.Delete<RoleAuthorize>().Where(a => a.RoleID == id).ExecuteAffrows();
            });
        }

        /// <summary>
        /// 后台查询数据（分页）
        /// </summary>
        /// <param name="req">分页查询请求对象</param>
        public PagingResult<T> Query<T>(PagingRequest req)
        {
            var select = fsql.Select<Role>();
            foreach (var item in req.FilterItems)
            {
                switch (item.Field)
                {
                    case "RoleID":
                        select.Where(a => a.RoleID == int.Parse(item.Value));
                        break;
                    case "RoleType":
                        select.Where(a => a.RoleType == int.Parse(item.Value));
                        break;
                    //case "RoleName":
                    //    select.Where(a => a.RoleName.Contains(item.Value));
                    //    break;
                    default:
                        break;
                }
            }

            if (!string.IsNullOrEmpty(req.SortExp))
            {
                select.OrderBy(req.SortExp);//自定义排序
            }
            else
            {
                select.OrderByDescending(a => a.RoleID);//默认排序
            }

            var sql = select.ToSql();

            var list = select.Count(out var total).Page(req.PageIndex, req.PageSize).ToList<T>();
            return new PagingResult<T>
            {
                PageIndex = req.PageIndex,
                PageSize = req.PageSize,
                Data = list,
                Total = (int)total
            };
        }

        public PagingResult<Role> Query(PagingRequest req)
        {
            return Query<Role>(req);
        }
        #endregion

        /// <summary>
        /// 获取角色字典数据
        /// </summary>
        public Dictionary<int, string> GetDic(int roleType = 0)
        {
            var dic = fsql.Select<Role>()
                .WhereIf(roleType > 0, a => a.RoleType == roleType)
                .Limit(10000)
                .ToDictionary(a => a.RoleID, a => a.RoleName); //ToDictionary(a => a.Id, a => new { a.Id, a.Title });
            return dic;
        }

        /// <summary>
        /// 获取租户角色列表
        /// </summary>
        /// <returns></returns>
        public List<T> GetList<T>(int roleType = 0)
        {
            var list = fsql.Select<Role>().WhereIf(roleType > 0, a => a.RoleType == roleType).ToList<T>();
            return list;
        }

        /// <summary>
        /// 修改系统角色
        /// </summary>
        public int Modify(RoleDto dto)
        {
            var item = GetItem<Role>(dto.RoleID) ?? throw new AppException($"系统角色不存在：{dto.RoleID}");
            var update = fsql.Update<Role>(dto.RoleID).Set(a => a.ModifyTime, DateTime.Now);
            if (dto.RoleName != item.RoleName) update.Set(a => a.RoleName, dto.RoleName);
            //if (dto.IsEnable != item.IsEnable) update.Set(a => a.IsEnable, dto.IsEnable);
            if (dto.Memo != item.Memo) update.Set(a => a.Memo, dto.Memo);

            return update.ExecuteAffrows();
        }

    }
}
